const app = getApp()
const userDao = require('../dao/userDao')

function formatTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function getDate(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}

function dayDiff(dateEnd) {
  const dateStart = new Date()

  return Math.floor(Math.abs(dateEnd - dateStart) / (1000 * 60 * 60 * 24))
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function getNavHeight() {
  let menu = wx.getMenuButtonBoundingClientRect()
  let statusH = wx.getSystemInfoSync().statusBarHeight
  let titeBar = (menu.top - statusH) + menu.bottom
  return titeBar
}

function hasCache(key) {
  const value = wx.getStorageSync(key)
  if (value) {
    if (dayDiff(new Date(value['saveTime'])) > 1) {
      return false
    } else {
      console.log("hasCache: " + key + ' value: ' + JSON.stringify(value['data']))
      return value['data']
    }
  } else {
    return false
  }
}

function setCache(key, data) {
  console.log("setCache: " + key)
  wx.setStorage({
    key: key,
    data: {
      'data': data,
      'saveTime': new Date().getTime()
    }
  })
}

function checkCurrentUser(callback) {
  let cacheUser = hasCache(app.keys.currentUser)
  if (cacheUser) {
    app.data.currentUser = cacheUser
    callback()
    return cacheUser
  } else {
    //请求用户信息
    userDao.where({
        '_openid': app.data.userInfo._openid
      })
      .then(res => {
        console.log(res)
        let user = res.data[0]
        if (user) {
          app.data.currentUser = user
          setCache(app.keys.currentUser, user)
          callback()
        } else {
          wx.navigateTo({
            url: '../user-data-add/user-data-add',
          })
        }

      })

  }

}

function checkLogin() {
  let user = hasCache(app.keys.userInfo)
  if (user) {
    return true
  } else {
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        getOpenId(res.userInfo)
      }
    })
  }
}

/**
 * 获取 OpenId
 */
function getOpenId(userInfo) {
  wx.showLoading({
    title: '加载中...',
  });
  wx.cloud.callFunction({
    name: 'quickstartFunctions',
    data: {
      type: 'getOpenId'
    }
  }).then((res) => {
    console.log(res);
    userInfo._openid = res.result.openid
    setCache(app.keys.userInfo, userInfo)
    app.data.userInfo = userInfo
    wx.hideLoading();
  }).catch((e) => {
    console.log(e);
    wx.hideLoading();
  });
}

function rpxTopx(rpx) {
  return rpx / 750 * wx.getSystemInfoSync().windowWidth
}

function pxTorpx(px) {
  return px * 750 / wx.getSystemInfoSync().windowWidth
}

module.exports = {
  formatTime,
  getNavHeight,
  rpxTopx,
  pxTorpx,
  dayDiff,
  getDate,
  hasCache,
  setCache,
  checkLogin,
  checkCurrentUser
}